<template>
  <div class="box-bg-color">
    <div class="filter-container">
      <div class="filter-item">
        <el-select v-model="searchReq.status" clearable style="width: 100px" placeholder="请选择">
          <el-option label="展示" :value="1">
            <k-badge type="primary" content="展示"></k-badge>
          </el-option>
          <el-option label="隐藏" :value="0">
            <k-badge type="danger" content="隐藏"></k-badge>
          </el-option>
        </el-select>
      </div>
      <div class="filter-item">
        <el-input v-model="searchReq.title" placeholder="请输入Banner标题" style="width: 200px" clearable></el-input>
      </div>
      <div class="filter-item">
        <el-button type="primary" @click="searchEvent">搜索</el-button>
      </div>
      <div class="filter-action-wrapper upload-wrap">
        <div class="filter-item">
          <el-button type="primary" v-perm="'home:banner:add'" @click="clickAddEvent">新增轮播图</el-button>
        </div>
      </div>
    </div>

    <k-table
      ref="tableRef"
      v-bind="tableData"
      :callback="getBannerListApi"
      :loading="loading"
      stripe
      current-row-key="id"
    >
      <template #img="{ row }">
        <Image :file="row.img"></Image>
      </template>
      <template #wapImg="{ row }">
        <Image :file="row.wapImg"></Image>
      </template>
      <template #status="{ row }">
        <k-badge
          :type="row.status === 1 ? 'primary' : 'danger'"
          :content="row.status === 1 ? '展示' : '隐藏'"
        ></k-badge>
      </template>
      <template #actions="{ row }">
        <el-button type="primary" plain size="small" @click="clickEditEvent(row.id)" v-perm="'home:banner:edit'"
          >编辑</el-button
        >
        <el-button type="info" plain size="small" @click="clickDeleteEvent(row)" v-perm="'home:banner:delete'"
          >删除</el-button>
        <el-button
          :type="row.status ? 'danger' : 'success'"
          plain
          size="small"
          @click="forbiddenEvent(row)"
           v-perm="'home:banner:updateStatus'"
        >
          {{ row.status ? '隐藏' : '展示' }}
        </el-button>
      </template>
    </k-table>

    <!-- banner编辑 -->
    <Edit v-model="showEdit" :curr-id="currId" @change="updateBannerSuccess"></Edit>

    <!-- banner添加 -->
    <Add v-model="showAdd" @change="createBannerSuccess"></Add>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, type UploadRawFile } from 'element-plus'
import type { IKTableProps } from 'k-ui'

import appConfig from '@/config/index'
import { getToken } from '@/utils/cache'
import { confirmElBox, dateStrFormat, downLoad } from '@/utils'
import Image from '@/components/Image/index.vue'

import {
  getBannerList,
  updateStatus,
  deleteBanner,
  getBannerAllList,
  type QueryBannerList,
  type BannerApiResult
} from '@/api/banner'

import type { ListResultData, Pagination } from '@/api/base'
import Edit from './components/Edit.vue'
import Add from './components/add.vue'
import { hasPerms } from '@/utils/perm'
import { useApiLock } from '_hooks'

const tableRef = ref()
const tableData = ref<IKTableProps<BannerApiResult>>({
  mode: 'config',
  data: { list: [], total: 0 },
  auto: true,
  isPager: true,
  pageSize: 20,
  index: true,
  columns: [
    { label: '标题', prop: 'title', default: '--' },
    { label: '跳转链接', prop: 'url', default: '--' },
    { label: 'PC端图片', prop: 'img', slot: true },
    { label: '移动端图片', prop: 'wapImg', slot: true },
    { label: '状态', prop: 'status', slot: true, width: 100 },
    {
      label: '创建时间',
      prop: 'createDate',
      formatter: (row: BannerApiResult) => dateStrFormat(row.createDate as string),
      width: 100
    }
  ]
})

/* 这里判断是否有整个操作列的权限；如果没有则不显示整列 */
const hasActionPerm = hasPerms(['home:banner:edit', 'home:banner:updateStatus', 'home:banner:delete'])
hasActionPerm && tableData.value.columns.push({ label: '操作', prop: 'actions', slot: true, width: 240 })

const loading = ref<boolean>(false)

const searchReq = ref<QueryBannerList>({
  page: 1,
  size: 20,
  status: '',
  title: ''
})
// 查询表格事件
const queryReq = ref<QueryBannerList>({ page: 1, size: 20 })

const getBannerListApi = async ({ page, size }: Pagination) => {
  loading.value = true
  const res = await useApiLock(() => getBannerList({ ...queryReq.value, page, size } as QueryBannerList), 500)
  // const resb = await useApiLock(() => getBannerAllList(), 500)
  // console.log(resb)
  loading.value = false
  if (res?.code === 200) {
    const data = res.data as ListResultData<BannerApiResult>
    data.list.forEach(item => {
      item.img = `${appConfig.api.staticUrl}${item.img}`
      item.wapImg = `${appConfig.api.staticUrl}${item.wapImg}`
    })
    tableData.value.data = data
  } else {
    ElMessage({ message: res?.msg || '网络异常，请稍后重试', type: 'error' })
  }
}

const updateBannerSuccess = (newPage = {}) => {
  // 在当前页 重新加载数据
  tableRef.value.refreshData(newPage)
}

const createBannerSuccess = (newPage = {}) => {
  // 在当前页 重新加载数据
  tableRef.value.refreshData(newPage)
}

const searchEvent = () => {
  queryReq.value = Object.assign({}, searchReq.value)
  updateBannerSuccess({ page: 1, size: 10 })
}

// Banner编辑
const showEdit = ref<boolean>(false)
const currId = ref<string | undefined>(undefined)
const clickEditEvent = (id: string) => {
  currId.value = id
  showEdit.value = true
}

// Banner添加
const showAdd = ref<boolean>(false)
const clickAddEvent = () => {
  showAdd.value = true
}

// 禁用 or 启用 逻辑
const forbiddenEvent = async (row: BannerApiResult) => {
  confirmElBox(`是否确认将Banner【${row.title}】${row.status === 1 ? '隐藏' : '恢复正常使用'}吗？`, async () => {
    loading.value = true
    const res = await updateStatus({ id: row.id, status: row.status === 1 ? 0 : 1 })
    loading.value = false
    if (res?.code === 200) {
      ElMessage({ type: 'success', message: `${row.status === 1 ? '隐藏' : '展示'}成功` })
      updateBannerSuccess()
    } else {
      ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
    }
  })
}

const clickDeleteEvent = async (row: BannerApiResult) => {
  confirmElBox(`是否确认将Banner【${row.title}】删除吗？`, async () => {
    loading.value = true
    const res = await deleteBanner({ id: row.id, isDelete: 0 })
    loading.value = false
    if (res?.code === 200) {
      ElMessage({ type: 'success', message: `删除成功` })
      updateBannerSuccess()
    } else {
      ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
    }
  })
}

</script>

<style lang="scss" scoped>
.user-account-wrap {
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.upload-wrap {
  display: flex;
}
</style>
